package controllers;

import models.User;
import play.cache.Cache;

public class Security extends Secure.Security {

	//@Override
	private static final String USER_KEY = "user";
	
	
	static boolean authenticate(final String username, final String password) {
		return User.count("byPseudoAndPassword", username, password) > 0;
    }
	
	
	static void onAuthenticated() {
		User user = User.find("byPseudo", Secure.Security.connected()).first();
		//TODO Cache.set(session.getId() + USER_KEY, user, "120mn");
		Cache.set(USER_KEY, user, "120mn");
    }

     /**
     * This method is called before a user tries to sign off.
     * You need to override this method if you wish to perform specific actions (eg. Record the name of the user who signed off)
     */
    static void onDisconnected() {
    	//TODO Cache.delete(session.getId() + USER_KEY);
    	Cache.delete(USER_KEY);
    }
    
    
    public static User getConnectedUser() {
    	//TODO User connectedUser = (User) Cache.get(session.getId() + USER_KEY);
    	User connectedUser = (User) Cache.get(USER_KEY);
    	if (connectedUser == null) {
    		//TODO Secure.logout();
    		//TODO remove these 3 lines 
    		User user = User.find("byPseudo", "flo").first();
    		Cache.set("user", user, "120mn");
    		connectedUser = (User) Cache.get(USER_KEY);
    	}
    	return connectedUser;
    }
   
	public static String getSessionId() {
		return session.getId();
	}
}
